<template>
  <div class="common-layout">
    <el-row class="header" type="flex" justify="space-between" align="middle">
      <el-col :span="12" style="text-align: right">
        <span>欢迎来到家政服务平台</span>
      </el-col>
      <el-col :span="12" style="text-align: right;">
        <el-form inline="inline">
          <el-form-item>
            <el-button-group v-if="!isLoggedIn" >
              <el-button type="primary" @click="login">登录</el-button>
              <el-button type="primary" @click="register">注册</el-button>
            </el-button-group>
            <el-dropdown trigger="click" v-else style="margin-right: 20px;">
              <el-button>
                {{currentCust.username}}
                <el-icon><arrow-down/></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="router.push('/custInfo')">个人空间</el-dropdown-item>
                  <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <div v-if="disable">
      <el-row>
        <el-col :span="24">
          <el-carousel :interval="4000" type="card" height="200px" class="carousel">
            <el-carousel-item v-for="(item, index) in advertisements" :key="index">
              <img :src="item.image" alt="advertisement" class="carousel-image"/>
            </el-carousel-item>
          </el-carousel>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <h3>我们的服务</h3>
          <ul>
            <li
                v-for="service in services"
                :key="service.id"
                @click="selectService(service)"
                :class="{ active: selectedService.id === service.id }"
            >
              {{ service.name }}
            </li>
          </ul>
        </el-col>
        <el-col :span="18">
          <div class="service-description">
            <div class="sub-service-icon">
              <img :src="selectedService.icon" alt="子服务类型图标"/>
            </div>
            <h2>服务介绍</h2>
            <p>{{ selectedService.description }}</p>
            <ul>
              <li
                  v-for="subService in selectedService.subServices"
                  :key="subService.id"
                  @click="selectSubService(subService)"
                  class="sub-service-item"
                  @mouseover="hoverSubService(subService)"
                  @mouseout="unhoverSubService"
              >
                {{ subService.name }}
              </li>
            </ul>
            <div style="border: darkgreen solid 2px;border-radius: 5px;width: 300px;margin: auto;;">
              <p style="font-weight: bold;font-size: 20px;color:mediumvioletred;">{{coupon.name}}</p>
              <el-button type="primary" @click="getCoupon(coupon)">获取该优惠券</el-button>
            </div>
            <h2>联系我们</h2>
            <p>{{ contactInfo }}</p>
          </div>
        </el-col>
      </el-row>
    </div>
    <div v-if="!disable" style="height: 80%; position: relative;">
      <el-button style="color:gray" circle @click="goBack" class="back-button"><el-icon><Back /></el-icon></el-button>
      <a id="top" href='#' ><el-button style="color:gray;position: fixed;top: 20px;right: 20px;z-index: 1000;" circle><el-icon><Top /></el-icon></el-button>
      </a>

      <!-- 服务详情展示 -->
      <div style="padding: 20px;">
        <el-card shadow="always" style="position: relative;">
          <div style="text-align: center;">
            <h2>{{ selectedService.name }}</h2>
            <p>{{ selectedService.description }}</p>
          </div>

          <!-- 子服务列表 -->
          <div v-for="subService in findService" :key="subService.id" style="margin-bottom: 20px;">
            <el-card shadow="always" style="position: relative;">
              <div style="text-align: center;">
                <h3>{{ subService.name }}</h3>
                <p>{{ subService.description }}</p>
                <p>{{"价格:"+subService.price}}</p>
                <p>{{"周期:"+subService.cycle}}</p>
              </div>

              <!-- 按钮容器 -->
              <div style="display: flex; justify-content: flex-end; margin-top: 20px;">
                <el-button type="primary" @click="placeOrder(subService)">下单</el-button>
                <el-button type="primary" @click="showFeedback(subService.id)">相关订单评价</el-button>
                <el-button type="success" @click="contactCustomerService(subService.name)" style="margin-left: 10px;">联系客服</el-button>
              </div>
            </el-card>
          </div>
        </el-card>
      </div>

      <el-dialog v-model="sessionDisabled" title="联系客服" style="width: 700px">
        <template #title>
          <div class="dialog-header">
            <span>联系客服</span>
            <el-button type="text" @click="toggleMinimize" style="float: right; padding: 3px 0;">
              {{ isMinimized ? '还原' : '最小化' }}
            </el-button>
          </div>
        </template>
        <div v-if="!isMinimized">
          <p>客服在线时间段是9:00-21:00，客服不在线时请留言，我们会尽快回复您</p>
          <el-tabs v-model="editableTabsValue" type="border-card" tab-position="left"
                   @tab-click="handleTabClick" >
            <el-tab-pane v-for="item in editableTabs" :label="item.title" :name="item.name">
              <div :id="`chat-container-${item.name}`" style="overflow-y: auto;height: 400px;width: 100%;border: #1989fa solid 5px;border-radius: 5px;">
                <ul :id="`chat-${item.name}`" style="list-style: none">
                </ul>
              </div>
              <el-input v-model="messages[item.name]" @keydown.enter.prevent="sendMessage(item.name)" type="text" style="width: 80%;"></el-input>
              <el-button @click="sendMessage(item.name)" type="primary" style="width:20%">发送</el-button>
            </el-tab-pane>
          </el-tabs>

          <el-button @click="showHistory" type="danger">查询历史消息</el-button>

          <el-dialog title="历史消息" v-model="messageDialogVisible"
                     :close-on-click-modal="false" style="width:70%;padding:40px;">
            <el-card>
              <el-form inline="inline">
                <el-form-item>
                  <el-input v-model="searchMessage.message" @keydown.enter.prevent="loadMessage" placeholder="搜索聊天记录"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button @click="custMessage" type="primary">显示客户信息</el-button>
                  <el-button @click="csMessage" type="primary">显示客服信息</el-button>
                  <el-button @click="resetMessage" type="primary">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
            <el-card>
              <el-table :data="historyMessage" >
                <el-table-column type="index" label="编号" width="80" align="center"></el-table-column>
                <el-table-column prop="custName" v-if="colDisableCust" label="客户名" align="center">
                  <template #default="scope" >
                    <span v-if="scope.row.custName=='不存在'">{{scope.row.custName}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="csName" v-if="colDisableCs" label="客服名" align="center">
                  <template #default="scope">
                    <span v-if="scope.row.csName=='不存在'">{{scope.row.csName}}</span>
                  </template>
                </el-table-column>
                <el-table-column  prop="message" label="消息" align="center"></el-table-column>
                <el-table-column  prop="createTime" label="发送时间" align="center"></el-table-column>
              </el-table>
            </el-card>
          </el-dialog>
        </div>
      </el-dialog>

      <!-- 最小化后的图标 -->
      <div v-if="isMinimized" class="minimized-dialog">
        <el-button type="text" @click="toggleMinimize">联系客服</el-button>
      </div>

      <el-dialog v-model="orderDialogVisible" title="订单">
        <el-form label-width="80px" label-position="top">
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="用户名">
                <el-input placeholder="请输入内容" v-model="order.custName" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="总价">
                <el-input v-model="order.totalPrice" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="备注信息">
                <el-input placeholder="请输入内容" v-model="order.remark" disabledd></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地址">
                <el-input placeholder="请输入内容" v-model="order.custAddress"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="选择优惠券">
                <el-select placeholder="请选择" v-model="order.couponId" @change="calPrice">
                  <el-option v-for="item in custCoupon" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="服务">
                <el-input disabled v-model="order.serviceName"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <el-button @click="saveOrder" type="primary">提交订单</el-button>
          <el-button @click="handleClose">返回</el-button>
        </template>
      </el-dialog>

      <el-dialog v-model="feedbackDialogVisible" title="相关订单评价">
        <el-card v-for="(item,index) in feedbackArrays" :key="item.id" style="border: grey solid 2px;border-radius: 10px;">
          <el-row>
            <el-col :span="8">
              评价时间：{{item.createTime}}
            </el-col>
            <el-col :span="4">
              评价星级：{{item.starRating}}
            </el-col>
            <el-col :span="8">
              <el-button id="likeButton" @click="addLikes(index,item)"><el-icon><Star /></el-icon>{{item.likes}}</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              用户评价：{{item.evaluate}}
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              客服回复：{{item.feedback}}
            </el-col>
          </el-row>
        </el-card>
      </el-dialog>

      <!-- 广告弹窗 -->
      <div style="width: 70px; height: 150px; position: fixed; top: 30vh; right: 5vw; z-index: 2" v-if="adc">
        <el-icon @click="adc = false" style="position: absolute; top: 2px; right: 2px;">
          <CloseBold/>
        </el-icon>
        <img src="01.png" style="width: 70px; height: 150px;">
      </div>
    </div>
    <el-row class="footer">
      <el-col :span="24">
        <span>版权所有 © 2024 家政服务平台</span>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import {ref, onMounted, computed, nextTick, watch} from 'vue';
import { useRouter } from 'vue-router';
import {VideoCameraFilled, CloseBold, Back, ArrowDown} from "@element-plus/icons-vue";
import axios from "axios";
import {ElMessage} from "element-plus";

const router = useRouter();

const advertisements = ref([
  { image: 'ad01.jpg' },
  { image: 'ad02.jpeg' },
  { image: 'ad03.jpeg' }
]);
const feedbackDialogVisible= ref(false);
const disable = ref(true);
const adc = ref(true);
const services = ref([
  {
    id: 6,
    name: '家庭清洁',
    description: '提供全方位的家庭清洁服务，包括厨房、卫生间、卧室等区域的深度清洁。',
    icon: 'householdCleaning.jpg',
    subServices: [
      {id: 101, name: '深度清洁', description: '包括厨房、卫生间等重点区域的深度清洁'},
      {id: 102, name: '日常清洁', description: '提供每日的基础清洁服务'}
    ]
  },
  {
    id: 7,
    name: '搬家服务',
    description: '专业搬家团队，安全高效，搬家无忧。',
    icon: 'movingServices.jpg',
    subServices: [
      {id: 201, name: '小型搬家', description: '适合单身公寓或小户型的搬家服务'},
      {id: 202, name: '大型搬家', description: '适合大户型或多层住宅的搬家服务'},
      {id: 203, name: '企业搬迁', description: '为企业提供的办公地点迁移服务'}
    ]
  },
  {
    id: 8,
    name: '育儿指导',
    description: '提供专业的育儿知识和技巧指导，帮助您更好地照顾孩子。',
    icon: 'parentingGuidance.jpg',
    subServices: [
      {id: 301, name: '婴儿护理指导', description: '针对新生儿家长的育儿知识培训'},
      {id: 303, name: '亲子游戏设计', description: '设计有助于亲子关系的游戏活动'},
      {id: 304, name: '早期教育咨询', description: '提供关于幼儿早期教育的建议'}
    ]
  },
  {
    id: 9,
    name: '金牌月嫂',
    description: '提供专业的护理知识，帮助您更快更好的调理身体。',
    icon: 'jpys.png',
    subServices: [
      {id: 401, name: '产后恢复指导', description: '为产妇提供科学的产后身体恢复方案'},
      {id: 403, name: '新生儿护理', description: '提供新生儿洗澡、换尿布等日常护理'}
    ]
  },
  {
    id: 10,
    name: '家电维修',
    description: '提供各种家电的维修服务，让您省心省力。',
    icon: 'homeApplianceMaintenance.jpg',
    subServices: [
      {id: 501, name: '制冷/热电器', description: '提供制冷/热电器的维修服务'},
      {id: 502, name: '清洁电器', description: '各种清洁电器的故障排查和修理'},
      {id: 504, name: '视听娱乐电器', description: '修复电视机、音响等设备的各种常见故障'}
    ]
  },
  {
    id: 11,
    name: '家居保养',
    description: '提供家居保养服务，让您的家居环境更加舒适。',
    icon: 'homeMaintenance.jpg',
    subServices: [
      {id: 601, name: '家居维护', description: '修补各类家居'},
      {id: 607, name: '家居翻新', description: '翻新各类家居'}
    ]
  }
]);
const selectedService = ref(services.value[0])
const contactInfo = ref('电话: 123-456-7890 | 邮箱: service@homemaid.com');
const isLoggedIn = ref(false);
const hoveredSubService = ref(null);
const findService=ref([])
const currentCust=ref({})
const selectService = (service) => {
  selectedService.value = service;
};

const selectSubService = (subService) => {
  console.log('Selected Sub Service:', subService);
  axios.post(BASE_URL+'/v1/dsService/selectByParentId',{parentId:subService.id})
      .then((response)=>{
        if (response.data.code==2000){
          adc.value = false;
          findService.value = response.data.data;
          console.log(findService.value)
          document.getElementById("top").click();
        }else {
          ElMessage.error(response.data.msg)
        }
      })
  disable.value = false;
};


const login = () => {
  router.push({path: '/custLogin'});
};

const register = () => {
  router.push({path: '/custLogin'});
};

const logout = () => {
  isLoggedIn.value = false;
  axios.get(BASE_URL+'/v1/customer/logout')
      .then((response)=>{
        if (response.data.code==2000){
          ElMessage.success("退出登录")
        }else {
          ElMessage.error(response.data.msg)
        }
      })

};

const hoverSubService = (subService) => {
  hoveredSubService.value = subService;
};

const unhoverSubService = () => {
  hoveredSubService.value = null;
};

const goBack = () => {
  disable.value = true;
  if (services.value.length > 0) {
    selectedService.value = services.value[0];
  }
};
const showFeedback = (id) => {
  if (isLoggedIn.value){
    serviceId = id
    feedbackDialogVisible.value=true
    getFeedback()
  }else {
    ElMessage.error("请先登录")
    router.push({path:'/custLogin'})
  }

}

const feedbackArrays=ref([])
const orderArrays=ref([])
let serviceId
const getFeedback=async ()=>{
  await axios.post(BASE_URL+'/v1/order/select',{serviceId:serviceId})
      .then((response)=>{
        if (response.data.code==2000){
          orderArrays.value=response.data.data
        }else {
          ElMessage.error(response.data.msg)
        }
      })
  console.log(orderArrays.value)
  for(let i=0;i<orderArrays.value.length;i++){
    axios.post(BASE_URL+'/v1/feedback/select',{orderId:orderArrays.value[i].id})
        .then((response)=>{
          if (response.data.code==2000){
            for(let j=0;j<response.data.data.list.length;j++){
              feedbackArrays.value.push(response.data.data.list[j])
            }
          }else {
            ElMessage.error(response.data.msg)
          }
        })
  }
  console.log(feedbackArrays.value)
}
const addLikes= async (index,item)=>{
  await axios.post(BASE_URL+'/v1/feedback/save',{id:item.id,likes:item.likes+1})
      .then((response)=>{
        if (response.data.code==2000){
          ElMessage.success("点赞成功")
          feedbackArrays.value[index].likes+=1
        }else {
          ElMessage.error(response.data.msg)
        }
      })
}
const sessionDisabled=ref(false)
const orderDialogVisible=ref(false)
const order=ref({})
const custCoupon=ref([])
const getCustCoupon = () => {
  console.log(currentCust.value)
  if (currentCust.value.coupon!=null){
    for (let c of currentCust.value.coupon){
      axios.post(BASE_URL+'/v1/coupon/select',{id:c})
          .then((response)=>{
            if (response.data.code==2000){
              custCoupon.value.push(response.data.data[0])
            }else {
              ElMessage.error(response.data.msg)
            }
          })
    }}
}
const calPrice = async () => {
  await axios.post(BASE_URL+'/v1/coupon/select',{id:order.value.couponId})
      .then((response)=>{
        if (response.data.code==2000){
          order.value.coupon=response.data.data[0]
        }else {
          ElMessage.error(response.data.msg)
        }
      })
  let c=order.value.coupon
  if (c.type==10){
    let effect=c.effect.split(',')
    if (order.value.totalPrice>=effect[0]){
      order.value.totalPrice-=effect[1]
      order.value.couponEffect=c.effect
    }else {
      ElMessage.error("该优惠券效果不满足")
      order.value.couponId=null
    }
  }else if (c.type==20){
    order.value.totalPrice*=c.effect
    order.value.couponEffect=c.effect
  }else if (c.type==30){
    order.value.totalPrice-=c.effect
    order.value.couponEffect=c.effect
  }
}
const placeOrder= (service)=>{
  if (isLoggedIn.value){
    custCoupon.value=[]
    order.value = {}
    orderDialogVisible.value=true
    order.value.serviceId=service.id
    order.value.serviceName=service.name
    order.value.custId=currentCust.value.id
    order.value.custName=currentCust.value.username
    order.value.custAddress=currentCust.value.address
    order.value.totalPrice=service.price
    getCustCoupon()
  }else {
    ElMessage.error("请先登录")
    router.push('/custLogin')
  }
}
const saveOrder = () => {
  axios.post(BASE_URL+'/v1/order/save',order.value)
    .then((response)=>{
      if (response.data.code==2000){
        if (order.value.couponId!=null){
          currentCust.value.coupon.splice(currentCust.value.coupon.indexOf(order.value.couponId),1)
          axios.post(BASE_URL+'/v1/customer/save',currentCust.value)
              .then((response)=>{
                if (response.data.code==2000){
                  getCust(currentCust)
                }else {
                  ElMessage.error(response.data.msg)
                }
              })
        }
        ElMessage.success("下单成功")
        orderDialogVisible.value=false
      }else {
        ElMessage.error(response.data.msg)
      }
    })
}
const handleClose = () => {
  if (confirm('确定关闭窗口？')){
    orderDialogVisible.value=false
  }
}

const contactCustomerService =async (name) => {
  if (isLoggedIn.value){
    await getCust(currentCust);
    initSocket(editableTabs.value[0]);
    sessionDisabled.value=true
  }else {
    ElMessage.error("请先登录")
    router.push('/custLogin')
  }
  
}
const messages = ref({})
const messageArr = ref([])

const editableTabsValue=ref(1)
const editableTabs=ref([
  {title:'新会话',name:1},
])
const sockets=ref([])
let sessionArr=[]

const addTab = async () => {
  await axios.post(BASE_URL+'/v1/webSessionMessage/session/select',{custId:currentCust.value.id})
      .then((response)=>{
        if (response.data.code==2000){
          if (sessionArr.length===0){
            sessionArr=response.data.data
            if (sessionArr.length>0){
              editableTabs.value=[]
              let s=sessionArr[0]
              editableTabs.value.push({title: '客服'+s.csId+'号',name: 1,sessionId:s.id,times:0})
            }
          }
        }else {
          ElMessage.error(response.data.msg)
        }
      })
}


const handleTabClick = (item) => {
  if (!sockets.value[item.name]){
    initSocket(item)
  }
}
const initSocket = (tab) => {
  if (tab.name===undefined){
    return
  }

  const wsUrl = "ws://localhost:10900/chat";
  sockets.value[tab.name] = new WebSocket(wsUrl);

  sockets.value[tab.name].onmessage = function (event) {
    const data = JSON.parse(event.data);
    if (data.sessionId!=null){
      let boolean=true
      for (let e of editableTabs.value){
        if (e.sessionId===data.sessionId){
          boolean=false
          break
        }
      }
      if (boolean){
        addTab()
        return
      }
    }
    const chatElement = document.getElementById(`chat-${tab.name}`);
    if (chatElement) {
      if (data.csId == null) {
        chatElement.innerHTML += `<li style="text-align: right;margin-bottom: 10px;"><span style="border: black solid 1px;display: inline-block;margin-right: 10px;padding: 5px;word-break:break-word;text-align: left;">${data.message}</span><span>${data.custName}</span></li>`;
      } else {
        chatElement.innerHTML += `<li style="text-align: left;margin-bottom: 10px;"><span>${data.csName}</span><span style="border: black solid 1px;display: inline-block;margin-left: 10px;padding: 5px;word-break:break-word;text-align: left;">${data.message}</span></li>`;
        if (tab.name!==editableTabsValue.value){
          editableTabs.value[tab.name-1].time+=1
        }
      }
    }
  };

  sockets.value[tab.name].onopen = function (event) {
    if(currentCust.value.id==null){
      getCust()
    }
    if (!messageArr.value[tab.name]) {
      messageArr.value[tab.name] = {};
    }

    if (editableTabs.value[tab.name-1].sessionId!=null){
      messageArr.value[tab.name].sessionId=editableTabs.value[tab.name-1].sessionId
    }
    messageArr.value[tab.name].custId=currentCust.value.id
    messageArr.value[tab.name].custName=currentCust.value.username
    messageArr.value[tab.name].message="连接成功"

    sendMessage(tab.name)
    console.log("连接成功");
  };

  sockets.value[tab.name].onclose = function (event) {
    console.log("连接关闭", event.code, event.reason);
    reconnect=true
    if (event.code !== 1000) {
      console.log(`尝试重连...`);
      // 设置重连定时器
      reconnectTimeouts.value[tab.name] = setTimeout(() => {
        initSocket(tab); // 递归调用 initSocket 尝试重连
      }, 10000);
    }
  };

};
let reconnect=false
// 为每个 WebSocket 实例维护一个重连定时器
const reconnectTimeouts = ref({});


const sendMessage = (tabName) => {
  if (!messages.value[tabName]) {
    messages.value[tabName] = "";
  }
  if (messages.value[tabName] !== '' && messages.value[tabName].trim()) {
    messageArr.value[tabName].message = messages.value[tabName];
  }
  if (messageArr.value[tabName].message === "" || !messageArr.value[tabName].message.trim()) {
    ElMessage.error("请输入内容");
    messages.value[tabName] = "";
    return;
  }
  if (sockets.value[tabName]) {
    sockets.value[tabName].send(JSON.stringify(messageArr.value[tabName]));
  }
  messageArr.value[tabName].message = ""
  messages.value[tabName] = ""
  scrollToBottom(tabName)
}

const scrollToBottom = (tabName) => {
  nextTick(() => {
    setTimeout(() => {
      const chatContainer = document.getElementById(`chat-container-${tabName}`);
      if (chatContainer) {
        chatContainer.scrollTop = chatContainer.scrollHeight;
      }
    }, 1);
  });
}

const historyMessage=ref([])
const searchMessage=ref({})
const messageDialogVisible=ref(false)

let sessionId
const showHistory = async () => {
  messageDialogVisible.value=true
  sessionId=editableTabs.value[editableTabsValue.value-1].sessionId
  searchMessage.value={sessionId:sessionId}
  await loadMessage()
}
const loadMessage = async () => {
  await axios.post(BASE_URL+'/v1/webSessionMessage/message/select',searchMessage.value)
      .then((response)=>{
        if (response.data.code==2000){
          historyMessage.value=response.data.data
          searchMessage.value={sessionId:sessionId}
        }else {
          ElMessage.error(response.data.msg)
        }
      })
}
const colDisableCs=ref(true)
const colDisableCust=ref(true)

const csMessage = () => {
  searchMessage.value={sessionId:sessionId}
  loadMessage().then(()=>{
    historyMessage.value=historyMessage.value.filter(item=>item.csId!=null)
  })
  colDisableCs.value=true
  colDisableCust.value=false
}
const custMessage = () => {
  searchMessage.value={sessionId:sessionId}
  loadMessage().then(()=>{
    historyMessage.value=historyMessage.value.filter(item=>item.custId!=null)
  })
  colDisableCs.value=false
  colDisableCust.value=true
}
const resetMessage = () => {
  searchMessage.value={sessionId:sessionId}
  loadMessage()
  colDisableCs.value=true
  colDisableCust.value=true
}
watch(editableTabsValue,(newVal)=>{
  handleTabClick({name:newVal})
})

const isMinimized=ref(false)
const toggleMinimize = () => {
  isMinimized.value = !isMinimized.value;
  nextTick(()=>{
    if (isMinimized.value){
      sessionDisabled.value=false
    }else {
      sessionDisabled.value=true
    }
  })
}
const coupon=ref({})
const loadCoupon = async () => {
  await axios.post(BASE_URL+'/v1/coupon/select',{id:1})
      .then((response)=>{
        if (response.data.code==2000){
          coupon.value=response.data.data[0]
        }else {
          ElMessage.error(response.data.msg)
        }
      })
}
const getCoupon = async (c) => {
  console.log(c)
  if (currentCust.value==null){
    router.push('/custLogin')
    return
  }
  if (currentCust.value.coupon==null){
    currentCust.value.coupon=[]
  }
  if (c.issuedQuantity-c.usedQuantity>0 && c.status==10){
    currentCust.value.coupon.push(c.id)
    await axios.post(BASE_URL+'/v1/customer/save',currentCust.value)
        .then((response)=>{
          if (response.data.code==2000){
            ElMessage.success("获取成功")
            getCust(currentCust)
          }else {
            ElMessage.error(response.data.msg)
          }
        })
    c.usedQuantity+=1
    await axios.post(BASE_URL+'/v1/coupon/save',c)
        .then((response)=>{
          if (response.data.code==2000){
          }else {
            ElMessage.error(response.data.msg)
          }
        })
  }else {
    ElMessage.error("优惠券已领完")
  }


}
onMounted(async () => {
  if (services.value.length > 0) {
    selectedService.value = services.value[0];
  }
  await getCust(currentCust)
  if(Object.keys(currentCust.value).length==0){
    console.log(isLoggedIn.value)
    console.log(currentCust.value)
    isLoggedIn.value=false
  }else {
    isLoggedIn.value=true
  }
  await loadCoupon()
});

</script>

<style scoped>
.common-layout {
  font-family: Arial, sans-serif;
  background-color: #f5f7fa;
}

.service-description {
  text-align: center;
}

.service-description h2 {
  margin-top: 20px;
  color: #303133;
}

.service-description p {
  color: #606266;
  line-height: 1.5;
  margin: 10px 0;
}

.service-description ul {
  list-style-type: none;
  padding: 0;
  margin: 10px 0;
}

.service-description ul li {
  margin: 10px 0;
  padding: 10px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.service-description ul li:hover {
  background-color: #ecf5ff;
  color: #409eff;
}

.service-description ul li.active {
  background-color: #ecf5ff;
  color: #409eff;
  font-weight: bold;
}

.header {
  background-color: #409eff;
  color: white;
  padding: 10px 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.el-dropdown-link {
  cursor: pointer;
  color: white;
}

.el-button-group {
  margin-right: 20px;
}

.footer {
  background-color: #409eff;
  color: white;
  text-align: center;
  padding: 10px 0;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
}

.el-row {
  margin-bottom: 20px;
}

.el-col {
  padding: 10px;
}

.el-carousel {
  width: 100%;
  overflow: hidden;
  margin-bottom: 20px;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.carousel-image:hover {
  transform: scale(1.05);
}

.sub-service-icon {
  text-align: center;
  margin: 20px 0;
}

.sub-service-icon img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  transition: transform 0.3s;
}

.sub-service-icon img:hover {
  transform: scale(1.1);
}

h2 {
  margin-top: 20px;
  color: #303133;
}

p {
  color: #606266;
  line-height: 1.5;
}

ul {
  list-style-type: none;
  padding: 0;
}

ul li {
  margin: 10px 0;
  padding: 10px;
  cursor: pointer;
  transition: background-color 0.3s;
}

ul li:hover {
  background-color: #ecf5ff;
  color: #409eff;
}

ul li.active {
  background-color: #ecf5ff;
  color: #409eff;
  font-weight: bold;
}

.back-button {
  position: fixed;
  top: 20px;
  left: 20px;
  z-index: 1000;
}
/* 最小化图标样式 */
.minimized-dialog {
  position: fixed;
  bottom: 10px;
  right: 10px;
  z-index: 9999;
}

.minimized-dialog .el-button {
  padding: 5px 10px;
  font-size: 14px;
  background-color: #1989fa;
  color: white;
  border-radius: 5px;
}

/* 隐藏默认的关闭按钮 */
.el-dialog__headerbtn {
  display: none;
}

/* 自定义标题栏样式 */
.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
